import axios, { AxiosInstance, AxiosRequestConfig, AxiosError } from 'axios';

interface PluginOptions {
    baseURL?: string | ((env: string) => string);
    timeout?: number;
    environment?: 'development' | 'test' | 'production';
    onError?: (error: AxiosError) => void; // 用户自定义错误处理函数
}

const createHttpClient = (options: PluginOptions = {}): AxiosInstance => {
    const { environment = 'development', baseURL, onError, timeout = 10000 } = options;

    // 解析 baseURL：如果是函数，根据环境返回相应的值；否则直接使用 baseURL
    const resolvedBaseURL = typeof baseURL === 'function' 
    ? baseURL(environment) 
    : baseURL || (() => {
        switch (environment) {
          case 'production':
            return 'https://api.production.com';
          case 'test':
            return 'https://api.test.com';
          default:
            return 'https://api.dev.com';
        }
      })();

    // 创建 Axios 实例
    const httpClient = axios.create({
        baseURL: resolvedBaseURL,
        timeout,
    });

    // 添加请求拦截器（可选）
    httpClient.interceptors.request.use(
        (config: AxiosRequestConfig) => {
        // 在发送请求之前做些什么
        return config;
        },
        (error: AxiosError) => {
        // 对请求错误做些什么
        return Promise.reject(error);
        }
    );

    // 全局错误处理
    httpClient.interceptors.response.use(
        (response: any) => response,
        (error: AxiosError) => {
            if(onError) {
                onError(error);
            } else {
                if (error.response) {
                    console.error('Response Error:', error.response.data);
                    switch (error.response.status) {
                    case 401:
                        console.error('Unauthorized');
                        break;
                    case 403:
                        console.error('Forbidden');
                        break;
                    case 500:
                        console.error('Server Error');
                        break;
                    default:
                        console.error('Unhandled Error:', error.response.status);
                    }
                } else if (error.request) {
                    console.error('No Response:', error.request);
                } else {
                    console.error('Request Error:', error.message);
                }
            }

            return Promise.reject(error);
        }
    );

    return httpClient;
};

export default createHttpClient;